package com.yan.aspect;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.yan.model.R;
import jdk.Exported;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 内部api调用异常处理
     */
    @ExceptionHandler(value = ApiException.class)
    public R handlerApiException(ApiException exception){
        IErrorCode errorCode = exception.getErrorCode();
        if (errorCode!=null){
            return R.failed(errorCode);
        }
        return R.failed(exception.getMessage());
    }

    /**
     * 方法参数校验失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError!=null){
                return R.failed(fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        return R.failed(exception.getMessage());
    }

    /**
     * 对象内部使用Validate 没有校验成功异常
     */
    @ExceptionHandler(BindException.class)
    public R handlerBindException(BindException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError!=null){
                return R.failed(fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        return R.failed(exception.getMessage());
    }

}
